/*
Copyright 2010-2011 CumulusCloud
http://cumuluscloud.cc

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package cumulusCloud.knowledge;

import java.io.File;
import java.io.FilenameFilter;

import cumulusCloud.common.InformationPath;


public class ApplicationKnow {
	static private ApplicationKnow instance;
	
	public static ApplicationKnow getInstance() {
		if (instance == null) instance = new ApplicationKnow();
		return instance;
	}
	
	private ApplicationKnow() {
		
	}

	public boolean deleteApplication(String appName) {
		String warPath = InformationPath.getCloudAppsInstallPath() + appName + ".war";
		File warFile = new File(warPath);
		return warFile.delete();
	}
	
	public String getApplicationIconURL(String appName) {
		String result = "/_appLauncher/default_icon32.png";
		
		// Check if application exists
		File base = new File(InformationPath.getCloudAppsInstallPath() + appName);
		if (!base.exists()) return null;
		
		// In the application
		base = new File(InformationPath.getCloudAppsInstallPath() + appName);
		if (base.exists()) {
			// Search for icon-32.*
			String[] fileList = base.list(new FilenameFilter() {
				@Override
				public boolean accept(File dir, String name) {
					return name.startsWith("icon-32.");
				}
			});
			
			if (fileList.length != 0) {
				result = "/" + appName + "/" + fileList[0];
			} else {
				if (new File(base.getAbsolutePath() + File.separatorChar + "favicon.ico").exists()) {
					result = "/" + appName + "/favicon.ico";
				}
			}
		}
		
		if (result.startsWith("/ROOT")) {
			result = result.substring(5);
		}
		
		
		return result;
	}

	public String[] listApplicationsDirsNames() {
		File base = new File(InformationPath.getCloudAppsInstallPath());
		
		String[] result = base.list(new FilenameFilter() {
			@Override
			public boolean accept(File dir, String name) {
				File next = new File(dir.getAbsolutePath() + File.separatorChar + name);
				if ( (next.isDirectory()) && (!name.equals("ROOT")) ) return true;
				return false;
			}
		});
		
		return result;
	}
}
